<template>
	<view class="container">
		<view class="v-header">
			<view class="v-header-left">上午专场</view>
			<view class="v-header-right">
				<text v-if="datas.StartQiangGou == true">正在抢购</text>
				<text v-if="datas.StartQiangGou == false">距离抢购</text>
				<view class="v-header-daojishi-h">{{ datas.TimeRemaining_H }}</view>
				<view class="v-header-daojishi-m">{{ datas.TimeRemaining_M }}</view>
				<view class="v-header-daojishi-s">{{ datas.TimeRemaining_S }}</view>
			</view>
		</view>
		<view class="v-content">
			<view class="v-product-item" v-for="(item, index) in datas.Products">
				<view class="v-product-item-img">
					<image :src="getServerPath(item.ImageUrl)" mode="aspectFill"></image>
				</view>
				<view class="v-product-item-title">
					{{ item.Title }}
					<view class="v-product-item-count">* {{ getProductCount(item) }}箱</view>
				</view>
				<view class="v-product-item-group">
					<view class="v-product-item-price">￥{{ item.Price }}</view>
					<button :loading="item.IsLoading" class="v-product-item-op"
						:class="datas.StartQiangGou === true && item.State === 1 ? 'v-product-item-op-active' : ''"
						@click="qiangGou(item)">
						抢购
					</button>
				</view>
			</view>
		</view>
		<view class="v-refresh" v-on:click="refresh">
			<image src="../../static/refresh.png" mode="aspectFit"></image>
			<text>刷新</text>
		</view>
		<uni-popup ref="message" type="message" class="pop-msg">
			<uni-popup-message :type="msgType" :message="messageText" :duration="600"></uni-popup-message>
		</uni-popup>
		<!-- 提示窗示例 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="warn" cancelText="关闭" confirmText="确定" title="提醒" :content="dialogMsg"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		dateUtils,
		authTokenUtil,
		validLoginToken
	} from '../../common/util.js';
	export default {
		data() {
			return {
				messageText: '',
				msgType: 'success',
				duration: 600,
				datas: {
					CurUser: null,
					SysQiangGouTime_HourStart: 10,
					SysQiangGouTime_MinuteStart: 30,
					SysQiangGouTime_HourEnd: 10,
					SysQiangGouTime_MinuteEnd: 40,
					TimeRemaining: '',
					TimeRemaining_H: '',
					TimeRemaining_M: '',
					TimeRemaining_S: '',
					StartQiangGou: false,
					Timer: null,
					Products: [
						// {
						// 	Id: '0000-000-000-0000',
						// 	Title: '智利欢乐马288干红葡萄酒干红葡萄酒干红葡萄酒干红葡萄酒',
						// 	ImageUrl: '../../static/header.jpg',
						// 	Price: '2889.36',
						// 	OriginalPrice: '3899.99',
						// 	BuyCount: 4,
						// 	CanQiangGou: true,
						// 	CreateTime: '2024-04-05 12:23',
						// 	Source: 1 //1:平台自营 2:商家运营
						// }
					]
				}
			};
		},
		methods: {
			getProductCount: function(item) {
				return parseInt(item.Price / 499) || 0;
			},
			receiveSocketMessage: function(msg) {
				console.log('receiveSocketMessage');
				let _this = this;
				var pro = JSON.parse(msg);
				if (pro && pro.Id) {
					var curPro = _this.datas.Products.find((p) => p.Id == pro.Id);
					if (curPro) {
						curPro.State = 0;
						console.log(`产品已被抢购：【${msg}】`);
					}
				}
			},
			sendSocketMessage: function(msg) {
				uni.sendSocketMessage({
					data: `${JSON.stringify({ arguments: [msg], target: 'SendMessage', type: 1 })}${String.fromCharCode(0x1e)}`
				});
			},
			connectSocket: function() {
				let _this = this;
				console.log('connectSocket');
				//signalr得连接地址并携带token
				// let url = "ws://xxx/xxxHub"+ '?access_token=xxxx';
				let url =
				`${_this.sysInfo.HubBasePath}hubs/sysmsghub`; //wss://localhost:5001/hubs/sysmsghub'; //这里 ws对的是Http://localhost:5000地址 ； wss对的是Http://localhost:5001

				//开始连接
				uni.connectSocket({
					url: url,
					method: 'GET',
					success: function() {}
				});
				//连接成功
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开！');

					//告诉服务器使用 JSON 的形式进行消息的序列化
					uni.sendSocketMessage({
						data: `{"protocol":"json", "version":1}${String.fromCharCode(0x1e)}`
					});
					//测试发送消息
					//_this.sendSocketMessage('12313');
				});
				//连接失败
				uni.onSocketError(function(res) {
					console.log(res, 'WebSocket连接打开失败，1秒后重连！');
					setTimeout(function() {
						//开始连接
						uni.connectSocket({
							url: url,
							method: 'GET',
							success: function() {}
						});
					}, 1000);
				});
				//接收到服务端消息
				uni.onSocketMessage(function(res) {
					var msg = res.data.replace(String.fromCharCode(0x1e), ''); //替换消息结束符

					let msgData = JSON.parse(msg);
					//接收指定消息（这里为服务端得ReceiveMessage得消息，msgData.type === 1 为固定值表示调用客户端的一个方法）
					if (msgData.type === 1 && msgData.target == 'ReceiveMessage') {
						console.log('收到服务器内容：' + JSON.stringify(msgData.arguments[0]));
						_this.receiveSocketMessage(msgData.arguments[0]);
					}
				});
				//断开时得方法
				uni.onSocketClose(function(res) {
					console.log('WebSocket 已关闭！');
				});
			},

			loadSysQiangGouTime: function(callback) {
				let _this = this;
				//正式代码
				var authToken = authTokenUtil();

				uni.request({
					url: _this.sysInfo.BasePath + 'RushPurchase/GetSettings',
					method: 'POST',
					data: null,
					header: {
						'content-type': 'application/json',
						Authorization: `${authToken}`
					},
					success: (res) => {
						if (res && res.data && res.data.Succeeded === true) {
							console.log(res);
							_this.datas.SysQiangGouTime_HourStart = res.data.Data
							.SysQiangGouTime_HourStart;
							_this.datas.SysQiangGouTime_MinuteStart = res.data.Data
								.SysQiangGouTime_MinuteStart;
							_this.datas.SysQiangGouTime_HourEnd = res.data.Data.SysQiangGouTime_HourEnd;
							_this.datas.SysQiangGouTime_MinuteEnd = res.data.Data
							.SysQiangGouTime_MinuteEnd;

							callback();
						} else {
							_this.sysUtils.tip({
								sender: _this,

								title: '加载抢购时间设置失败！',
								icon: 'error'
							});
						}
					},
					fail: () => {
						_this.sysUtils.tip({
							sender: _this,
							title: '加载抢购时间设置失败！',
							icon: 'error'
						});
					},
					complete: () => {}
				});
			},
			dialogConfirm() {
				console.log('点击确认');
				let _this = this;
				_this.del_Post();
			},
			dialogClose() {
				console.log('点击关闭');
			},
			getServerPath: function(url) {
				let _this = this;
				console.log(`${_this.sysInfo.ImageBasePath}${url}`);
				return `${_this.sysInfo.ImageBasePath}${url}`;
			},
			loadProducts: function(callback) {
				console.log('loadProducts');

				let _this = this;
				//正式代码
				var authToken = authTokenUtil();

				uni.request({
					url: _this.sysInfo.BasePath + 'RushPurchase/GetProductDatas',
					method: 'POST',
					data: {},
					header: {
						'content-type': 'application/json',
						Authorization: `${authToken}`
					},
					success: (res) => {
						if (res && res.data && res.data.Succeeded === true) {
							console.log(res);
							_this.datas.Products = res.data.Data.Datas;
							if (callback) {
								callback();
							}
						} else {
							_this.sysUtils.tip({
								sender: _this,

								title: '加载产品信息失败！',
								icon: 'error'
							});
						}
					},
					fail: () => {
						_this.sysUtils.tip({
							sender: _this,
							title: '加载产品信息失败！',
							icon: 'error'
						});
					},
					complete: () => {}
				});
				uni.stopPullDownRefresh();
			},
			refresh: function() {
				let _this = this;
				_this.loadProducts(() => {
					_this.sysUtils.tip({
						sender: _this,
						title: '加载产品信息成功！',
						icon: 'success'
					});
				});
			},
			async getNextQiangGouTime() {
				let _this = this;
				// 创建当前时间的Date对象
				let nowres = await _this.getServerTime();
				let now = new Date(nowres);
				console.log(now, 99992)
				let today_Start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), _this.datas
					.SysQiangGouTime_HourStart, _this.datas.SysQiangGouTime_MinuteStart, 0);
				let today_End = new Date(now.getFullYear(), now.getMonth(), now.getDate(), _this.datas
					.SysQiangGouTime_HourEnd, _this.datas.SysQiangGouTime_MinuteEnd, 0);
				let nextQiangGouTime = new Date(
					now.getFullYear(),
					now.getMonth(),
					now.getDate() + 1,
					_this.datas.SysQiangGouTime_HourStart,
					_this.datas.SysQiangGouTime_MinuteStart,
					0
				);

				// 获取三天时间的毫秒数
				const threeDays = 3 * 24 * 60 * 60 * 1000;
				if (_this.datas.CurUser && _this.datas.CurUser.IsVIP && _this.datas.CurUser.ApplyVIPTime) {
					if (now.getTime() - new Date(_this.datas.CurUser.ApplyVIPTime).getTime() < threeDays) {
						today_Start.setMinutes(today_Start.getMinutes() - 1);
					}
				}

				if (now < today_Start || (now >= today_Start && now < today_End)) {
					return today_Start;
				}
				return nextQiangGouTime;
			},
			async getTimeRemaining() {
				let _this = this;
				// 创建当前时间的Date对象
				let nowres = await _this.getServerTime();
				let now = new Date(nowres);
				console.log(now, 99992)
				let today_End = new Date(now.getFullYear(), now.getMonth(), now.getDate(), _this.datas
					.SysQiangGouTime_HourEnd, _this.datas.SysQiangGouTime_MinuteEnd, 0);
				return today_End - now;
			},
			getServerTime: function(callback) {
				let _this = this;
				//正式代码
				var authToken = authTokenUtil();
			
				return new Promise((resolve, reject) => {
					uni.request({
						url: _this.sysInfo.BasePath + 'Sys/GetSystemTime',
						method: 'POST',
						data: null,
						header: {
							'content-type': 'application/json',
							'Authorization': `${authToken}`
						},
						success: (res) => {
							if (res && res.data && res.data.Succeeded === true) {
								console.log(res)
								// 请求成功处理
								resolve(res.data.Data);
							} else {
								// 请求失败处理
								reject('获取服务器时间失败！');
							}
						},
						fail: () => {
							// 请求失败处理
							reject('获取服务器时间失败！');
						},
						complete: () => {}
					});
				});
			},
			
			qiangGou(item) {
				let _this = this;
				if (_this.datas.StartQiangGou === true && item.IsLoading !== true && item.State === 1) {
					//更改抢购按钮状态
					item.IsLoading = true;
					//更改是否允许抢购状态
					item.State = 0;

					//正式代码
					var authToken = authTokenUtil();
					//正式代码
					uni.request({
						url: _this.sysInfo.BasePath + 'RushPurchase/BuyProduct',
						method: 'Post',
						data: item,
						header: {
							'content-type': 'application/json',
							Authorization: `${authToken}`
						},
						success: (res) => {
							item.IsLoading = false;
							if (res && res.data) {
								if (res.data.Succeeded === true) {
									console.log('抢购产品成功！');

									_this.sysUtils.tip({
										sender: _this,
										title: '抢购产品成功！',
										icon: 'success'
									});
								} else {
									_this.sysUtils.tip({
										sender: _this,
										title: res.data.Errors,
										icon: 'error'
									});
								}
							} else {
								_this.sysUtils.tip({
									sender: _this,
									title: '抢购产品失败！',
									icon: 'error'
								});
							}
						},
						fail: () => {
							//更改抢购按钮状态
							item.IsLoading = false;
							_this.sysUtils.tip({
								sender: _this,
								title: '抢购产品失败！',
								icon: 'error'
							});
						},
						complete: () => {
							//更改抢购按钮状态
							item.IsLoading = false;
						}
					});
				}
			},
			computeNextQiangGouTime: async function() {
				let _this = this;
				let curTime = await _this.getServerTime();
				console.log(curTime, 99991)
				let nextQiangGouTime =await _this.getNextQiangGouTime();
				let current = new Date(curTime);
				let specified = new Date(nextQiangGouTime);

				// 计算时间戳差值（毫秒）
				let diff = specified - current;
				if (diff <= 0) {
					_this.datas.StartQiangGou = true;
				} else {
					_this.datas.StartQiangGou = false;

					// 将时间戳差值转换为总秒数
					let totalSeconds = Math.floor(diff / 1000);
					let totalMinutes = Math.floor(totalSeconds / 60);
					let totalHours = Math.floor(totalMinutes / 60);

					// 计算剩余的秒数和分钟数
					let remainingSeconds = totalSeconds % 60;
					let remainingMinutes = totalMinutes % 60;

					// 格式化输出结果
					_this.datas.TimeRemaining_H = totalHours.toString().padStart(2, '0');
					_this.datas.TimeRemaining_M = remainingMinutes.toString().padStart(2, '0');
					_this.datas.TimeRemaining_S = remainingSeconds.toString().padStart(2, '0');
				}
			},
			computeRemainTimeForStartQiangGou:async function() {
				let _this = this;

				let remainTime =await _this.getTimeRemaining();
				_this.datas.TimeRemaining = remainTime;
				if (remainTime <= 0) {
					_this.datas.TimeRemaining_H = '00';
					_this.datas.TimeRemaining_M = '00';
					_this.datas.TimeRemaining_S = '00';

					_this.datas.StartQiangGou = false;
					uni.navigateBack();
					// clearInterval(_this.Timer);
					return;
				} else {
					// 将时间戳差值转换为总秒数
					let totalSeconds = Math.floor(remainTime / 1000);
					let totalMinutes = Math.floor(totalSeconds / 60);
					let totalHours = Math.floor(totalMinutes / 60);

					// 计算剩余的秒数和分钟数
					let remainingSeconds = totalSeconds % 60;
					let remainingMinutes = totalMinutes % 60;

					_this.datas.TimeRemaining_H = totalHours.toString().padStart(2, '0');
					_this.datas.TimeRemaining_M = remainingMinutes.toString().padStart(2, '0');
					_this.datas.TimeRemaining_S = remainingSeconds.toString().padStart(2, '0');

					_this.datas.StartQiangGou = true;
				}
			},
			init: function() {
				console.log('init');
				let _this = this;
				_this.datas.StartQiangGou = false;
				if (_this.Timer) {
					clearInterval(_this.Timer);
				}
				uni.getStorage({
					key: 'CurrentUser',
					success: (res) => {
						console.log(res);
						_this.datas.CurUser = res.data;
					}
				});

				_this.loadProducts();
				// //测试代码开始
				// _this.datas.StartQiangGou = true;
				// return;
				// //测试代码结束

				//正式代码
				_this.loadSysQiangGouTime(() => {
					//正式代码
					_this.Timer = setInterval(async () => {
						if (_this.datas.StartQiangGou == false) {
							await  _this.computeNextQiangGouTime();
						} else {
							await _this.computeRemainTimeForStartQiangGou();
						}
					}, 1000);
				});
			}
		},
		onPullDownRefresh() {
			console.log('onPullDownRefresh');
			let _this = this;
			this.datas.Products = [];
			_this.loadProducts();
		},
		onShow() {
			let _this = this;
			// _this.init();
		},
		created() {
			let _this = this;
			validLoginToken(null, () => {
				uni.reLaunch({
					url: '/pages/account/login'
				});
			});
			_this.connectSocket();
			_this.init();
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: stretch;
	}

	.v-header {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: stretch;
		height: 100rpx;
		position: fixed;
		top: var(--window-top);
		left: 0;
		width: 100%;
		/* background-color: #333; */
		background-color: #fffffff0;
		z-index: 11;
		box-shadow: #999 0rpx 10rpx 10rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		color: #333;
		letter-spacing: 2rpx;
	}

	.v-header-left {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		flex: 1;
		font-weight: bold;
		font-size: 32rpx;
	}

	.v-header-right {
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
		align-items: center;
		flex: 2;
		font-weight: bold;
		font-size: 26rpx;
	}

	.v-header-right text {
		color: #c93a00ff;
		margin-right: 20rpx;
	}

	.v-header-right view {
		font-size: 32rpx;
		color: #fff;
		background-color: #c93a00ff;
		margin-right: 10rpx;
		padding: 5rpx;
		border-radius: 10rpx;
	}

	.v-content {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: stretch;
		margin-top: 100rpx;
		padding: 30rpx;
		box-sizing: border-box;
	}

	.v-product-item {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: stretch;
		width: 47%;
		margin-right: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: #999 1rpx 5rpx 5rpx;
	}

	.v-product-item:nth-child(2n) {
		margin-right: 0;
	}

	.v-product-item-img {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: stretch;
		width: 100%;
	}

	.v-product-item-img image {
		width: 100%;
		height: 200rpx;
	}

	.v-product-item-title {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: stretch;
		padding: 10rpx;
		font-size: 26rpx;
		flex: 1;
	}

	.v-product-item-count {
		margin-left: 10rpx;
	}

	.v-product-item-group {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: stretch;
		padding: 10rpx;
		box-sizing: border-box;
		margin-bottom: 20rpx;
	}

	.v-product-item-price {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		flex: 1;
		color: #ff5343;
		font-size: 30;
		font-weight: bold;
	}

	.v-product-item-op {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		align-self: flex-end;
		background-color: #bababa;
		color: #fff;
		font-size: 26rpx;
		height: 60rpx;
		width: 140rpx;
		border-radius: 10rpx;
		letter-spacing: 2rpx;
	}

	.v-product-item-op-active {
		background-color: #c93a00ff;
	}

	.v-product-item-group uni-button[loading]:before {
		margin-right: 5rpx;
	}

	.v-refresh {
		position: fixed;
		right: 20rpx;
		bottom: 120rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #ffffffdf;
		height: 120rpx;
		width: 120rpx;
		border-radius: 100rpx;
		border: solid 1px #1296db;
		box-shadow: #1296db 1rpx 5rpx 10rpx;
		font-size: 26rpx;
		color: #1296db;
		font-weight: bold;
	}

	.v-refresh image {
		height: 50rpx;
		width: 50rpx;
		margin-bottom: 10rpx;
	}

	.pop-msg ::v-deep .uni-popup-message-text {
		font-size: 32rpx !important;
	}
</style>